/**
 * 代码解析类，解析代码表达式
 */
import { is_const, is_data, is_action } from "../util";

export default class Resolver {
    constructor (okay, ele) {
        this.okay = okay
        this.ele = ele
    }
    resolve (code) {
        let vari = code.replace(/\s+/g, '').replace('{{', '').replace('}}', '')
        let t = vari.split(/\+|-|\*|\/|\(|\)|\?|>[=]?|<[=]?|={2}|:|&{2}|\|{2}/g)
        if (1 === t.length) {
            return this.resolve_chip(t[0], '')
        }else {
            let t1 = vari.match(/\+|-|\*|\/|\(|\)|\?|>[=]?|<[=]?|={2}|:|&{2}|\|{2}/g)
            let res = ''
            for (let j = 0; j < t1.length; j++) {
                res = this.resolve_chip(t[j], res) + t1[j]
            }
            return this.resolve_chip(t[t1.length], res)
        }
    }

    /**
     * 碎片处理
     */
    resolve_chip (chip, res) {
        let flag = false
        if (is_const(chip)) {
            return res + chip
        }
        // 过滤器提取
        let filter_chip = chip.split('|')
        let param = filter_chip[0]
        let param_code = ''
        if (param != '') {
            flag = false
            let pc = this.okay.subscribe(param, this.ele)
            if (!pc) {
                console.error('未定义数据：' + param + "=======" + chip)
            }else {
                param_code = pc
            }
            if (1 === filter_chip.length) {
                return res + param_code
            }
        } else {
            flag = true
            param_code = res
        }
        filter_chip.forEach((filter, key) => {
            if (key == 0) {
                return
            }
            let tt = filter.split(',')
            if (tt.length == 1) {
                param_code = 'this.filter(\'' + filter + '\',' + param_code + ')'
            } else {
                let param_arr = []
                for (let i = 1;i < tt.length;i++) {
                    let pm = tt[i]
                    if (is_const(pm)) {
                        param_arr.push(pm)
                        continue
                    }
                    let sub_pm = this.okay.subscribe(pm, this.ele)
                    if (!sub_pm) {
                        console.error('未定义数据：' + pm + "=======" + chip)
                    } else {
                        param_arr.push(sub_pm)
                    }
                }
                let params = param_arr.join(',')
                param_code = 'this.filter(\'' + tt[0] + '\',' + param_code + ',' + params + ')'
            }
        })
        return flag?param_code:(res + param_code)
    }
}